<?php


namespace app\admin\controller;


use app\common\model\ActivityModel;
use app\common\model\ActivityRewardModel;
use app\common\model\PropsModel;
use app\common\model\GiftModel;
use app\common\model\UserActivityModel;
use think\Db;
use think\facade\Env;
use think\facade\Request;

class ActivityController extends BaseController {

    public function index() {
        $web_uri = getConfigPub()->site_domain . '/activity';
        $this->assign('web_uri', $web_uri);
        return $this->fetch();
    }

    public function add() {
        // 礼物
        $gift_list = GiftModel::where(['type' => 2, 'status' => 1])->select();
        // 挂件
        $props_list = PropsModel::select();
        // 挂件时长数组
        $props_duration_cate = ActivityRewardModel::PROPS_DURATION_CATE;

        $this->assign('gift_list', $gift_list);
        $this->assign('props_list', $props_list);
        $this->assign("props_duration_cate", $props_duration_cate);
        return $this->fetch();
    }

    public function edit() {
        $id            = Request::param('id');
        $activity_info = ActivityModel::with('reward')->get($id);
        if(empty($activity_info)){
            return self::bulidFail("未查询到相关数据");
        }

        // 礼物id
        $activity_info->gift_id  = 0;
        $activity_info->gift_num = 0;
        $activity_info->carat = $activity_info->carat == 0 ? 0 : bcdiv($activity_info->carat, '100', 2);
        $activity_info->eagle_drill = $activity_info->eagle_drill == 0 ? 0 : bcdiv($activity_info->eagle_drill, '100', 2);
        // 挂件
        $props_reward = [];

        foreach ($activity_info->reward as $val) {
            switch ($val->reward_type) {
                case 3:
                    $activity_info->gift_id  = $val->gift_id;
                    $activity_info->gift_num = $val->quantity;
                    break;
                case 4:
                    $props_reward[] = [
                        'id'       => $val->props_id,
                        'duration' => $val->props_duration,
                    ];
                    break;
            }
        }
        unset($activity_info->reward);

        // 礼物
        $gift_list = GiftModel::where(['type' => 2, 'status' => 1])->select();
        // 挂件
        $props_list = PropsModel::order('weight DESC')->select();
        // 挂件时长数组
        $props_duration_cate = ActivityRewardModel::PROPS_DURATION_CATE;


        $this->assign('gift_list', $gift_list);
        $this->assign("props_list", $props_list);
        $this->assign("props_duration_cate", $props_duration_cate);
        $this->assign("props_reward", $props_reward);
        $this->assign('activity_info', $activity_info);
        return $this->fetch();
    }

    public function getactivitys() {

        $model = new ActivityModel;
        if (in_array($category = $this->get('category'), ['0', 1, 2])) {
            $model = $model->where('category', $category);
        }

        if ($title = Request::param('title')) {
            $model = $model->whereLike('title', '%' . $title . '%');
        }

        return json([
            "count" => $model->count('id'),
            "data" => $model->field('content', true)
                ->order('id DESC')
                ->page((int)$this->get('page', 1), (int)$this->get('limit', 20))
                ->select()->each(function ($query) {
                    $query->carat = $query->carat == 0 ? 0 : bcdiv($query->carat, '100', 2);
                    $query->eagle_drill = $query->eagle_drill == 0 ? 0 : bcdiv($query->eagle_drill, '100', 2);
                })
                ->toArray(),
            "code" => 0,
            "msg" => "",
        ]);
    }

    /**
     * 添加活动业务逻辑
     * @return \think\response\Json
     */
    public function add_post()
    {
        $all_param = Request::param();

        $all_param['category'] = 0;

        if ($all_param['category'] != 0) {
            if (!empty($all_param['bind_bankcard']) && is_numeric($all_param['bind_bankcard'])) {
                $all_param['bind_bankcard'] = 1;
            } else {
                $all_param['bind_bankcard'] = 0;
            }

            if (empty($all_param['carat']) || !is_numeric($all_param['carat'])) {
                $all_param['carat'] = 0;
            } else {
                $all_param['carat'] = bcmul($all_param['carat'], '100', 0);
            }

            if (empty($all_param['eagle_drill']) || !is_numeric($all_param['eagle_drill'])) {
                $all_param['eagle_drill'] = 0;
            } else {
                $all_param['eagle_drill'] = bcmul($all_param['eagle_drill'], '100', 0);
            }

            if (empty($all_param['experience']) || !is_numeric($all_param['experience'])) {
                $all_param['experience'] = 0;
            }
        } else {
            $all_param['bind_bankcard'] = 0;
            $all_param['carat'] = 0;
            $all_param['experience'] = 0;
            $all_param['eagle_drill'] = 0;
        }

        $activity = new ActivityModel($all_param);
        if (!$activity->start_time || !$activity->end_time) {
            return static::bulidFail('请输入活动起止时间');
        }

        if (strtotime($activity->start_time) >= strtotime($activity->end_time)) {
            return static::bulidFail('活动结束时间必须大于活动开始时间');
        }

        $activity->create_time = nowFormat();
        $activity->modify_time = nowFormat();
        $activity->manager_id = $this->admin_id;

        if (!$activity->save()) {
            return static::bulidFail();
        }

        parent::addAdminLog("添加活动，活动ID：{$activity->id}，标题：{$activity->title}");

        return static::bulidSuccess();
    }

    /**
     * 编辑活动业务逻辑
     * @return \think\response\Json
     */
    public function edit_post()
    {
        $all_param = Request::param();

        $id = Request::param('id');
        if (!$activity = ActivityModel::get($id)) {
            return static::bulidFail('活动信息不存在');
        }

        if (!$all_param['start_time'] || !$all_param['end_time']) {
            return static::bulidFail('请输入活动起止时间');
        }

        if (strtotime($all_param['start_time']) >= strtotime($all_param['end_time'])) {
            return static::bulidFail('活动结束时间必须大于活动开始时间');
        }

        if ($activity->category != 0) {
            if (!empty($all_param['bind_bankcard']) && is_numeric($all_param['bind_bankcard'])) {
                $all_param['bind_bankcard'] = 1;
            } else {
                $all_param['bind_bankcard'] = 0;
            }

            if (empty($all_param['carat']) || !is_numeric($all_param['carat'])) {
                $all_param['carat'] = 0;
            } else {
                $all_param['carat'] = bcmul($all_param['carat'], '100', 0);
            }

            if (empty($all_param['eagle_drill']) || !is_numeric($all_param['eagle_drill'])) {
                $all_param['eagle_drill'] = 0;
            } else {
                $all_param['eagle_drill'] = bcmul($all_param['eagle_drill'], '100', 0);
            }

            if (empty($all_param['experience']) || !is_numeric($all_param['experience'])) {
                $all_param['experience'] = 0;
            }
        } else {
            $all_param['bind_bankcard'] = 0;
            $all_param['carat'] = 0;
            $all_param['experience'] = 0;
            $all_param['eagle_drill'] = 0;
        }

        $activity->manager_id = $this->admin_id;
        $activity->modify_time = nowFormat();

        if (!$activity->save($all_param)) {
            return static::bulidFail('修改信息失败');
        }

        parent::addAdminLog("修改活动，活动ID：{$activity->id}，标题：{$activity->title}");

        return static::bulidSuccess();
    }

    public function del_post() {
        $id       = Request::param('activityid');
        $activity = ActivityModel::get($id);
        if (!$activity) {
            return self::bulidFail('未查询到相关活动');
        }

        if (ActivityModel::where(['id' => $id])->delete()) {
            // 记录日志
            $log_content = "删除活动，活动ID：{$activity->id}，标题：{$activity->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function uploadImage() {
        $img = Request::file('file');
        if (!empty($img)) {
            $filePaths = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . "uploads/image/activity";
            if (!file_exists($filePaths)) {
                mkdir($filePaths, 0777, true);
            }
            $info     = $img->validate(['ext' => 'jpg,png,jpeg'])->move($filePaths);
            $filename = $info->getSaveName();
            if ($filename) {
                if ($_SERVER['HTTP_HOST'] && $_SERVER['HTTP_HOST'] != 'localhost') {
                    $src = 'http://' . $_SERVER['HTTP_HOST'] . "/uploads/image/activity/" . $filename;
                } else {
                    $src = "/uploads/image/activity/" . $filename;
                }
                return json(['code' => 0, 'data' => ['src' => $src]]);
            } else {
                return json(["code" => 1, "msg" => "只能上传jpg,png,jpeg格式图片"]);
            }
        }
        return json(['code' => 1, 'msg' => '上传失败']);
    }

    /**
     * 活动领取记录
     */
    public function receive() {
        return $this->fetch();
    }

    /**
     * 奖励列表
     * @return \think\response\Json
     */
    public function receive_list()
    {
        $model = new UserActivityModel();
        if (is_numeric($uid = $this->get('uid'))) {
            $model = $model->where('uid', $uid);
        }

        if ($title = trim($this->get('title', ''))) {
            if (!$ids = ActivityModel::whereLike('title', "%{$title}%")->column('id')) {
                return json(["code" => 0, "msg" => "", "data" => [], "count" => 0]);
            }
            $model = $model->whereIn('activity_id', $ids);
        }

        if (in_array($category = $this->get('category'), ['0', 1, 2])) {
            $model = $model->where('category', $category);
        }

        $model = $model->where('is_received', 1);
        return json([
            "count" => $model->count('id'),
            "data" => $model->with(['activity'])
                ->order('id DESC')
                ->page($this->get('page', 1), $this->get('limit', 20))
                ->select()->each(function ($query) {
                    if ($query->activity) {
                        $query->carat = $query->activity->carat == 0 ? 0 : bcdiv($query->activity->carat, '100', 2);
                        $query->eagle_drill = $query->activity->eagle_drill == 0 ? 0 : bcdiv($query->activity->eagle_drill, '100', 2);
                        $query->experience = $query->activity->experience;
                    } else {
                        $query->carat = 0;
                        $query->eagle_drill = 0;
                        $query->experience = 0;
                    }
                })->toArray(),
            "code" => 0,
            "msg" => "",
        ]);
    }

}